package com.heixiu.gallery2

import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.*
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import kotlinx.android.synthetic.main.fragment_gallery.*

/**
 * 图片列表.
 */
class GalleryFragment : Fragment() {
    private var dyNum  = 0
    private val galleryViewModel by activityViewModels<GalleryViewModel>()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_gallery, container, false)
    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        super.onCreateOptionsMenu(menu, inflater)
        inflater.inflate(R.menu.overflow_menu, menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when(item.itemId) {
            R.id.overflowRefresh -> {
                swipeRefreshLayout.isRefreshing = true
                galleryViewModel.resetData()
            }
        }
        return super.onOptionsItemSelected(item)
    }


    @SuppressLint("RestrictedApi")
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        setHasOptionsMenu(true)

        with(floatingActionButtonToTop) {
            visibility = View.INVISIBLE
            setOnClickListener {
                dyNum = 0
                it.visibility = View.INVISIBLE
                recyclerView.scrollToPosition(0)
            }
        }

        val galleryAdapter = GalleryAdapter(galleryViewModel)
        recyclerView.apply {
            adapter = galleryAdapter
            //layoutManager = GridLayoutManager(requireContext(), 2)
            layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
        }

        galleryViewModel.photoListLiveData.observe(viewLifecycleOwner, Observer {
            galleryAdapter.submitList(it)
        })

        galleryViewModel.networkStatus.observe(viewLifecycleOwner, Observer {
            Log.d("mytag", it.toString())
            galleryAdapter.updateNetworkStatus(it)
            swipeRefreshLayout.isRefreshing = it == NetworkStatus.INITIAL_LOADING
        })

        swipeRefreshLayout.setOnRefreshListener {
            galleryViewModel.resetData()
        }
    }
}
